package com.bing.dao.impl;

import com.bing.dao.BaseDao;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * Created by Administrator on 2015/7/15.
 */
public class BaseDaoImpl<T, K extends Serializable> implements BaseDao<T, K> {

    private Class<T> clazz;

    public BaseDaoImpl() {
        ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
        clazz = (Class<T>) type.getActualTypeArguments()[0];
        System.out.println("DAO的真实实现类是：" + this.clazz.getName());
    }

    @Autowired
    private SessionFactory sessionFactory;

    private Session getSession() {
        return sessionFactory.openSession();
    }

    @Override
    public void save(T entity) {
        getSession().save(entity);
    }

    @Override
    public void update(T entity) {
        getSession().update(entity);
    }

    @Override
    public void delete(K id) {
        getSession().delete(findById(id));
    }

    @Override
    public T findById(K id) {
        return (T) getSession().get(clazz, id);
    }

    @Override
    public List<T> findByHQL(String hql, Object... params) {
        Query query = getQuery(hql, params);
        return query.list();
    }

    @Override
    public T findByHQLOne(String hql, Object... params) {
        Query query = getQuery(hql, params);
        return (T) query.uniqueResult();
    }

    private Query getQuery(String hql, Object[] params) {
        Query query = this.getSession().createQuery(hql);
        for (int i = 0; params != null && i < params.length; i++) {
            query.setParameter(i, params);
        }
        return query;
    }
}
